package com.dianqu.weather.core.dao.impl;

import java.sql.SQLException;
import java.util.List;

import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.orm.hibernate3.HibernateCallback;
import org.springframework.orm.hibernate3.HibernateTemplate;
import org.springframework.stereotype.Repository;

import com.dianqu.weather.core.dao.WeatherDao;
import com.dianqu.weather.core.entity.TWeather;

@Repository("weaherDao")
public class WeatherDaoImpl implements WeatherDao {

	@Autowired
	public HibernateTemplate hibernateTemplate;

	public TWeather getInfo(final String location) {

		return hibernateTemplate.execute(new HibernateCallback<TWeather>() {
			public TWeather doInHibernate(Session session)
					throws HibernateException, SQLException {
				String hql = "from TWeather where cityname=? order by datetime desc";
				Query query = session.createQuery(hql);
				query.setParameter(0, location);
				query.setMaxResults(1);
				List list = query.list();
				if (list.isEmpty())
					return null;
				return (TWeather) list.get(0);
			}
		});
	}

	public boolean saveInfo(TWeather weather) {
		hibernateTemplate.save(weather);
		return true;
	}

}
